from datetime import datetime
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Boolean
from sqlalchemy.orm import relationship
from lib.database import Base


class House(Base):
    __tablename__ = "house"

    id = Column(Integer, primary_key=True)
    link = Column(String(32), nullable=False, index=True, comment="该房子在链家/我爱我家 的链接")
    type_graph = Column(String(512), comment="户型图的链接")
    living_graph = Column(String(512), comment="客厅图的链接")
    type = Column(String(64), comment="房屋户型")
    floor = Column(String(32), comment="楼层")
    total_floors = Column(Integer, comment="总楼层")
    decoration = Column(String(32), comment="装修")
    size = Column(String(16), comment="建筑面积")
    attribute = Column(String(32), comment="房屋用途")
    pre_trading_date = Column(DateTime, default=None, comment="上次交易时间, 我爱我家无")
    age_limit = Column(String(32), default=None, comment="购房年限, 链家有上次交易时间，不采集该数据")
    code = Column(String(32), index=True, comment="房源核验统一编码")
    price = Column(Integer, comment="售价")
    focus_count = Column(Integer, default=None, comment="关注人数， 我爱我家无")
    is_sell_out = Column(Boolean, default=False, comment="是否已经出售(根据是否下架来判断)")
    sell_out_date = Column(DateTime, default=None, comment="出售的时间")

    house_dyn_list = relationship("HouseDyn", passive_deletes=True)
    community_id = Column(Integer, ForeignKey('community.id'))
    community = relationship("Community", backref="houses")

    def dict(self):
        """model 转 dic"""
        return {c.name: getattr(self, c.name) for c in self.__table__.columns}

    @property
    def is_lian_jia(self):
        return "lianjia.com" in self.link

    @property
    def is_wiwj(self):
        return "5i5j.com" in self.link

    @property
    def room_type(self):
        if self.type[:2] == "1室":
            return "一室"
        elif self.type[:2] == "2室":
            return "二室"
        elif self.type[:2] == "3室":
            return "三室"
        elif self.type[:2] == "4室":
            return "四室"
        else:
            return "四室以上"


class HouseDyn(Base):
    """房源的历史价格"""
    __tablename__ = "house_dyn"

    id = Column(Integer, primary_key=True)
    price = Column(Integer, comment="售价")

    house_id = Column(Integer, ForeignKey('house.id', ondelete='cascade'))
    created_at = Column(DateTime, comment="房源价格第一次变动的时间", default=datetime.utcnow)
